package com.oa.hr.user.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.BaseService;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.common.entity.SysUser;
import com.oa.common.service.SysUserService;
import com.oa.hr.skill.entity.HrSkillUser;
import com.oa.hr.skill.entity.HrSkillUserVo;
import com.oa.hr.skill.service.SkillUserService;
import com.oa.hr.user.entity.*;
import com.oa.hr.user.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/*/oa/hr/user/hrUserBaseInfo")
@Api(tags = {"员工其他信息表-操作接口"})
public class HrUserBaseInfoController {

    static Logger logger = LoggerFactory.getLogger(HrUserBaseInfoController.class);

    @Autowired
    private HrUserBaseInfoService hrUserBaseInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HrUserFamilyInfoService hrUserFamilyInfoService;
    @Autowired
    private HrUserRecordService hrUserRecordService;
    @Autowired
    private HrUserWorkedService hrUserWorkedService;
    @Autowired
    private HrUserEduRecordService hrUserEduRecordService;
    @Autowired
    private HrUserTrainService hrUserTrainService;
    @Autowired
    private HrUserCredentialService hrUserCredentialService;
    @Autowired
    private HrUserContractService hrUserContractService;
    @Autowired
    private HrUserIncentiveInfoService hrUserIncentiveInfoService;
    @Autowired
    private HrUserSalaryService hrUserSalaryService;
    @Autowired
    private HrUserPerHolidayService hrUserPerHolidayService;
    @Autowired
    private HrUserLeaveService hrUserLeaveService;
    @Autowired
    private HrUserDynamicallyService hrUserDynamicallyService;
    @Autowired
    private HrUserDimissionService hrUserDimissionService;
    @Autowired
    private HrUserOvertimeService hrUserOvertimeService;
    @Autowired
    private SkillUserService skillUserService;

    @ApiOperation(value = "员工其他信息表-查询列表", notes = " ")
    @ApiEntityParams(HrUserBaseInfo.class)
    @ApiResponses({@ApiResponse(code = 200, response = HrUserBaseInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = {"/list", "/listUserInfo"}, method = RequestMethod.GET)
    public Result listHrUserBaseInfo(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        RequestUtils.transformArray(params, "deptids");
        params.put("branchId", user.getBranchId());
        QueryWrapper<HrUserBaseInfo> qw = QueryTools.initQueryWrapper(HrUserBaseInfo.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = hrUserBaseInfoService.selectListMapByWhere(page, qw, params);

        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "员工其他信息表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = HrUserBaseInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addHrUserBaseInfo(@RequestBody HrUserBaseInfoVo hrUserBaseInfo) {


        User user = LoginUtils.getCurrentUserInfo();
        hrUserBaseInfo.setBranchId(user.getBranchId());
        if (!StringUtils.hasText(hrUserBaseInfo.getUserid())) {
            return Result.error("userid-null", "用户编号userid不能为空");
        }
        if (StringUtils.isEmpty(hrUserBaseInfo.getId())) {
            hrUserBaseInfo.setId(hrUserBaseInfoService.createKey("id"));
        } else {
            HrUserBaseInfo hrUserBaseInfoQuery = new HrUserBaseInfo(hrUserBaseInfo.getId());
            if (hrUserBaseInfoService.countByWhere(hrUserBaseInfoQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        List<Map<String, Object>> dpus = this.sysUserService.selectUserDeptPost(BaseService.map("userid", hrUserBaseInfo.getUserid(), "branchId", hrUserBaseInfo.getBranchId()));
        if (dpus != null && dpus.size() > 0) {
            Map<String, Object> dpu = null;
            Optional<Map<String, Object>> o = dpus.stream().filter(i -> "1".equals(i.get("master"))).findFirst();
            if (o.isPresent()) {
                dpu = o.get();
            } else {
                dpu = dpus.get(0);
            }
            hrUserBaseInfo.setDeptid((String) dpu.get("deptid"));
            String pdeptid = (String) dpu.get("deptid");
            hrUserBaseInfo.setDeptName((String) dpu.get("deptName"));
            if (!StringUtils.hasText(hrUserBaseInfo.getReportId())) {
                String manager = (String) dpu.get("manager");
                hrUserBaseInfo.setReportId(manager);
                hrUserBaseInfo.setReportName((String) dpu.get("managerName"));
                if (hrUserBaseInfo.getUserid().equals(manager)) {//如果当前人员是部门经理，则他的汇报上级应该是上级部门的部门经理
                    Map<String, Object> pdept = sysUserService.getDept(pdeptid);
                    manager = (String) pdept.get("manager");
                    hrUserBaseInfo.setReportId(manager);
                    hrUserBaseInfo.setReportName((String) pdept.get("managerName"));
                }
            }
            hrUserBaseInfo.setPost((String) dpu.get("postId"));
            hrUserBaseInfo.setPostName((String) dpu.get("postName"));
        }

        hrUserBaseInfoService.insert(hrUserBaseInfo);
        HrSkillUserVo hrSkillUserVo = new HrSkillUserVo();
        hrSkillUserVo.setSkillIds(hrUserBaseInfo.getSkillIds());
        hrSkillUserVo.setUserid(hrUserBaseInfo.getUserid());
        skillUserService.batchEdit(hrSkillUserVo);

        return Result.ok("add-ok", "添加成功！").setData(hrUserBaseInfo);
    }

    //上传的excel文件
    @PostMapping("addBaseInfoByExcel")
    public Result addSubject(MultipartFile file) {


        try {
            hrUserBaseInfoService.saveSubject(file, hrUserBaseInfoService);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return Result.ok("", "成功导入数据");
    }

    //回显员工信息
    @RequestMapping(value = "/getEmployeeInfo", method = RequestMethod.GET)
    public Result getEmployeeInfo(@RequestParam Map<String, Object> hrUserBaseInfo) {

        String userid = (String) hrUserBaseInfo.get("userid");
        if (!StringUtils.hasText(userid)) {
            return Result.error("员工编号userid必传");
        }
        QueryWrapper<HrUserBaseInfo> qw = QueryTools.initQueryWrapper(HrUserBaseInfo.class, hrUserBaseInfo);
        IPage page = QueryTools.initPage(hrUserBaseInfo);
        User user = LoginUtils.getCurrentUserInfo();
        hrUserBaseInfo.put("branchId", user.getBranchId());
        Map<String, Object> map = hrUserBaseInfoService.getEmployeeInfo(page, qw, hrUserBaseInfo);    //回显员工信息
        return Result.ok("", "查询成功").setData(map).setTotal(page.getTotal());
    }

    //查询员工信息列表
    @RequestMapping(value = "/listBaseInfoByDeriveType", method = RequestMethod.GET)
    public Result listBaseInfoByDeriveType(@RequestParam Map<String, Object> hrUserBaseInfo) {
        RequestUtils.transformArray(hrUserBaseInfo, "ids");

        User user = LoginUtils.getCurrentUserInfo();
        hrUserBaseInfo.put("branchId", user.getBranchId());
        List<Map<String, Object>> hrUserBaseInfoList = hrUserBaseInfoService.selectListBaseInfoByDeriveType(hrUserBaseInfo);
        return Result.ok("", "查询成功").setData(hrUserBaseInfoList);
    }

    @ApiOperation(value = "员工其他信息表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delHrUserBaseInfo(@RequestBody HrUserBaseInfo hrUserBaseInfo) {


        if (!StringUtils.hasText(hrUserBaseInfo.getId())) {
            return Result.error("id-null", "请上送id");
        }
        hrUserBaseInfo = this.hrUserBaseInfoService.selectOneObject(hrUserBaseInfo);
        User user = LoginUtils.getCurrentUserInfo();
        hrUserBaseInfo.setBranchId(user.getBranchId());
        hrUserBaseInfoService.deleteByPk(hrUserBaseInfo);
        HrUserFamilyInfo hrUserFamilyInfo = new HrUserFamilyInfo();
        hrUserFamilyInfo.setUserid(hrUserBaseInfo.getUserid());
        hrUserFamilyInfo.setBranchId(user.getBranchId());
        hrUserFamilyInfoService.deleteByWhere(hrUserFamilyInfo);
        HrUserRecord hrUserRecord = new HrUserRecord();
        hrUserRecord.setUserid(hrUserBaseInfo.getUserid());
        hrUserRecord.setBranchId(user.getBranchId());
        hrUserRecordService.deleteByWhere(hrUserRecord);
        HrUserWorked hrUserWorked = new HrUserWorked();
        hrUserWorked.setUserid(hrUserBaseInfo.getUserid());
        hrUserWorked.setBranchId(user.getBranchId());
        hrUserWorkedService.deleteByWhere(hrUserWorked);
        HrUserEduRecord hrUserEduRecord = new HrUserEduRecord();
        hrUserEduRecord.setUserid(hrUserBaseInfo.getUserid());
        hrUserEduRecord.setBranchId(user.getBranchId());
        hrUserEduRecordService.deleteByWhere(hrUserEduRecord);
        HrUserTrain hrUserTrain = new HrUserTrain();
        hrUserTrain.setUserid(hrUserBaseInfo.getUserid());
        hrUserTrain.setBranchId(user.getBranchId());
        hrUserTrainService.deleteByWhere(hrUserTrain);
        HrUserCredential hrUserCredential = new HrUserCredential();
        hrUserCredential.setUserid(hrUserBaseInfo.getUserid());
        hrUserCredential.setBranchId(user.getBranchId());
        hrUserCredentialService.deleteByWhere(hrUserCredential);
        HrUserContract hrUserContract = new HrUserContract();
        hrUserContract.setUserid(hrUserBaseInfo.getUserid());
        hrUserContract.setBranchId(user.getBranchId());
        hrUserContractService.deleteByWhere(hrUserContract);
        HrUserIncentiveInfo hrUserIncentiveInfo = new HrUserIncentiveInfo();
        hrUserIncentiveInfo.setUserid(hrUserBaseInfo.getUserid());
        hrUserIncentiveInfo.setBranchId(user.getBranchId());
        hrUserIncentiveInfoService.deleteByWhere(hrUserIncentiveInfo);
        HrUserSalary hrUserSalary = new HrUserSalary();
        hrUserSalary.setUserid(hrUserBaseInfo.getUserid());
        hrUserSalary.setBranchId(user.getBranchId());
        hrUserSalaryService.deleteByWhere(hrUserSalary);
        HrUserPerHoliday hrUserPerHoliday = new HrUserPerHoliday();
        hrUserPerHoliday.setUserid(hrUserBaseInfo.getUserid());
        hrUserPerHoliday.setBranchId(user.getBranchId());
        hrUserPerHolidayService.deleteByWhere(hrUserPerHoliday);
        HrUserLeave hrUserLeave = new HrUserLeave();
        hrUserLeave.setUserid(hrUserBaseInfo.getUserid());
        hrUserLeave.setBranchId(user.getBranchId());
        hrUserLeaveService.deleteByWhere(hrUserLeave);
        HrUserDynamically hrUserDynamically = new HrUserDynamically();
        hrUserDynamically.setUserid(hrUserBaseInfo.getUserid());
        hrUserDynamically.setBranchId(user.getBranchId());
        hrUserDynamicallyService.deleteByWhere(hrUserDynamically);
        HrUserDimission hrUserDimission = new HrUserDimission();
        hrUserDimission.setUserid(hrUserBaseInfo.getUserid());
        hrUserDimission.setBranchId(user.getBranchId());
        hrUserDimissionService.deleteByWhere(hrUserDimission);
        HrUserOvertime hrUserOvertime = new HrUserOvertime();
        hrUserOvertime.setUserid(hrUserBaseInfo.getUserid());
        hrUserOvertime.setBranchId(user.getBranchId());
        hrUserOvertimeService.deleteByWhere(hrUserOvertime);
        HrSkillUser hrSkillUser = new HrSkillUser();
        hrSkillUser.setUserid(hrUserBaseInfo.getUserid());
        skillUserService.deleteByWhere(hrSkillUser);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "员工其他信息表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = HrUserBaseInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editHrUserBaseInfo(@RequestBody HrUserBaseInfoVo hrUserBaseInfo) {


        SysUser u = new SysUser();
        u.setUserid(hrUserBaseInfo.getUserid());
        SysUser sysUser = sysUserService.selectOneObject(u);
        if (sysUser != null) {
            sysUser.setUserid(hrUserBaseInfo.getUserid());
            sysUser.setUsername(hrUserBaseInfo.getUsername());
            sysUser.setIdCardNo(hrUserBaseInfo.getIdCardNo());
            sysUser.setSex(hrUserBaseInfo.getSex());
            sysUser.setEmail(hrUserBaseInfo.getEmail());
            sysUser.setPhoneno(hrUserBaseInfo.getPhoneno());
            sysUserService.updateSomeFieldByPk(sysUser);
            List<Map<String, Object>> dpus = this.sysUserService.selectUserDeptPost(BaseService.map("userid", hrUserBaseInfo.getUserid(), "branchId", hrUserBaseInfo.getBranchId()));
            if (dpus != null && dpus.size() > 0) {
                Map<String, Object> dpu = null;
                Optional<Map<String, Object>> o = dpus.stream().filter(i -> "1".equals(i.get("master"))).findFirst();
                if (o.isPresent()) {
                    dpu = o.get();
                } else {
                    dpu = dpus.get(0);
                }
                hrUserBaseInfo.setDeptid((String) dpu.get("deptid"));
                String pdeptid = (String) dpu.get("deptid");
                hrUserBaseInfo.setDeptName((String) dpu.get("deptName"));
                if (!StringUtils.hasText(hrUserBaseInfo.getReportId())) {
                    String manager = (String) dpu.get("manager");
                    hrUserBaseInfo.setReportId(manager);
                    hrUserBaseInfo.setReportName((String) dpu.get("managerName"));
                    if (hrUserBaseInfo.getUserid().equals(manager)) {//如果当前人员是部门经理，则他的汇报上级应该是上级部门的部门经理
                        Map<String, Object> pdept = sysUserService.getDept(pdeptid);
                        manager = (String) pdept.get("manager");
                        hrUserBaseInfo.setReportId(manager);
                        hrUserBaseInfo.setReportName((String) pdept.get("managerName"));
                    }
                }
                hrUserBaseInfo.setPost((String) dpu.get("postId"));
                hrUserBaseInfo.setPostName((String) dpu.get("postName"));
            }
        }


        hrUserBaseInfoService.updateByPk(hrUserBaseInfo);
        HrSkillUserVo hrSkillUserVo = new HrSkillUserVo();
        hrSkillUserVo.setSkillIds(hrUserBaseInfo.getSkillIds());
        hrSkillUserVo.setUserid(hrUserBaseInfo.getUserid());
        skillUserService.batchEdit(hrSkillUserVo);

        return Result.ok("edit-ok", "修改成功！").setData(hrUserBaseInfo);
    }

    @ApiOperation(value = "员工其他信息表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = HrUserBaseInfo.class, props = {}, remark = "员工其他信息表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = HrUserBaseInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        hrUserBaseInfoService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "员工其他信息表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelHrUserBaseInfo(@RequestBody List<HrUserBaseInfo> hrUserBaseInfos) {
        User user = LoginUtils.getCurrentUserInfo();
        if (hrUserBaseInfos.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<HrUserBaseInfo> datasDb = hrUserBaseInfoService.listByIds(hrUserBaseInfos.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<HrUserBaseInfo> can = new ArrayList<>();
        List<HrUserBaseInfo> no = new ArrayList<>();
        for (HrUserBaseInfo data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            hrUserBaseInfoService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "员工其他信息表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = HrUserBaseInfo.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(HrUserBaseInfo hrUserBaseInfo) {
        HrUserBaseInfo data = (HrUserBaseInfo) hrUserBaseInfoService.getById(hrUserBaseInfo);
        return Result.ok().setData(data);
    }

    //查询最新的十条员工
    @RequestMapping(value = "/listNewWorker", method = RequestMethod.GET)
    public Result listNewWorker(@RequestParam Map<String, Object> hrUserBaseInfo) {
        RequestUtils.transformArray(hrUserBaseInfo, "ids");
        List<Map<String, Object>> hrUserBaseInfoList = hrUserBaseInfoService.selectListNewWorker(hrUserBaseInfo);

        return Result.ok("query-ok", "查询成功").setData(hrUserBaseInfoList);
    }

}
